﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using System.Threading;

namespace MyOpenGame
{
    public class Defence : AModel
    {
        private DefenderState _state;
        private int _attackRate;
        private Thread _attackThread;
        private bool _isThreadRunning;


        public Defence(int row, DefenderState state)
            : base(row)
        {
            _state = state;
            GameUtility gameUtility = new GameUtility();
            _points = gameUtility.GetDefenderPointsForRow(row);
            _texture = _state.GetTexture();
            _moveStep = 0;
            _lifePoints = _state.GetLifePoints();
            _attackRate = _state.GetAttackRate();

            _attackThread = new Thread(Attack);
            _attackThread.Start();
            _attackThread.IsBackground = true;
            _isThreadRunning = false;
        }

        public void SetState(DefenderState state)
        {
            _state = state;
            _texture = _state.GetTexture();
            _lifePoints = _state.GetLifePoints();
            _attackRate = _state.GetAttackRate();

            
            
        }

        public void ChangeState()
        {
            _state.ChangeState(this);
            _texture = _state.GetTexture();
            _lifePoints = _state.GetLifePoints();
            _attackRate = _state.GetAttackRate();
        }

        public void Upgrade(DefenderState state)
        {
            SetState(state);

            if (_attackThread.IsAlive)
            {
                _isThreadRunning = false;
            }

            _attackThread = new Thread(Attack);
            _isThreadRunning = true;
            _attackThread.Start();
            _attackThread.IsBackground = true;
        }

        public void ChangePotition(List<Vector2> newPotition)
        {
            _points = newPotition;
        }

        public void Attack()
        {
            while (_isThreadRunning)
            {
                if (_attackRate > 0)
                {
                    Ball ball = new Ball(_row);
                    Game.getInstance().AddModel(ball);
                }
                else
                {
                    _isThreadRunning = false;
                    break;
                }

                Thread.Sleep(_attackRate);
            }
        }
    }
}
